package com.zofer.study.optional;

import com.zofer.study.optional.entity.Address;
import com.zofer.study.optional.entity.User;

import java.util.Optional;

public class OptionalTest02 {

    public static void main(String[] args) {
        test1();
        test2();
        test3();
        test4();
    }

    /**
     * test1
     */
    public static void test1(){
        User user = null;
        user = Optional.ofNullable(user).orElse(createUser());
        user = Optional.ofNullable(user).orElseGet(() -> createUser());
        System.out.println(user);
    }


    /**
     * test2
     */
    public static void test2(){
        User user = null;
        try {
            user = Optional.ofNullable(user).orElseThrow(() -> new Exception("用户不存在"));
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }


    /**
     * test3
     */
    public static void test3() {
        User user = createUserAndAdrress();
        try {
            String sfd = Optional.ofNullable(user)
                    .map(s -> setAddress(s.getAddress()))
                    .map(a -> a.getProvince())
                    .orElseThrow(() -> new Exception("城市不存在"));
            System.out.println("===="+sfd);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    /**
     * test4
     * @return
     */
    public static User test4(){
        return Optional.ofNullable(createUser())
                .filter(u->"zhangsan".equals(u.getName()))
                .orElseGet(()-> {
                    User user1 = new User();
                    user1.setName("zhangsan11");
                    return user1;
                });
    }

    /**
     */
    public static Address setAddress(Address address){
        address.setProvince("756");
        return address;
    }



    public static User createUser(){
        User user = new User();
        user.setName("zhangsan");
        return user;
    }

    public static User createUserAndAdrress(){
        Address address = new Address();
        address.setProvince("广东省");
        address.setCity("深圳市");
        address.setArea("南山区");


        User user = new User();
        user.setName("zhangsan");
        user.setAddress(address);
        return user;
    }
}
